<?php

Raise::load('core.security.RaiseLimiter');

/**
 * TestCoreRaiseLimiter class
 * Testing unit of 'phpraise/core/RaiseLimiter.php'
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package Raise.UnitTest.Test
 */
class TestCoreRaiseLimiter extends RaiseTest {
    
    public static function testClass(){
        self::assertClassExists('RaiseLimiter');
        self::assertClassExtends('RaiseLimiter', 'RaiseHelper');
        self::assertConstantDefined('RaiseLimiter::SESSION_KEY');
    }

    public static function testRun(){
        // create a new limiter that allow 10 requests within 10 minutes
        $session = new RaiseSession();
        $session->start();
        $limiter = new RaiseLimiter($session, 'testLimiting', 10, new RaiseTimeSpan(600));
        self::assertObjectClass($limiter, 'RaiseLimiter');
        self::assertStrictEqual($limiter->max(), 10);
        self::assertObjectClass($limiter->lastReset(), 'RaiseDateTime');
        self::assertObjectClass($limiter->interval(), 'RaiseTimeSpan');
        self::assertStrictEqual($limiter->interval()->totalSeconds(), 600.0);
        self::assertStrictEqual($limiter->count(), 0);
        $limiter->addCount();
        self::assertStrictEqual($limiter->count(), 1);
        self::assertTrue($limiter->check());

        // let's test for exceeding limit
        for($i = 0; $i < 20; $i++){
            $limiter->addCount();
        }
        self::assertFalse($limiter->check());
        
        // test reset
        $limiter->reset();
        self::assertStrictEqual($limiter->count(), 0);
        self::assertTrue($limiter->check());

        $limiter->clear();
        unset($limiter);
        self::assertFALSE($session->get(RaiseLimiter::SESSION_KEY)->keyExists('testLimiting'));
    }

}
